import { Form, addToast } from "@heroui/react";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import LoginInput from "./LoginInput";
import { invoke } from "@tauri-apps/api/core";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
  get_user_object,
  save_user_info,
  reset_user_form,
} from "../../store/user/user";

const LoginForm = forwardRef(({ notify }, ref) => {
  const navigate = useNavigate();
  const user = useSelector((state) => state.user.user);
  const dispatch = useDispatch();
  //提交内容相关
  const reset = (payload) => {
    setSubmited(payload);
    return payload;
  };
  const [submited, setSubmited] = useState({
    id: 0,
    username: "",
    password: "",
  });
  const set_submited_username = (new_value) => {
    setSubmited((prev_submited) => {
      return {
        ...prev_submited,
        username: new_value,
      };
    });
  };
  const set_submited_password = (new_value) => {
    setSubmited((prev_submited) => {
      return {
        ...prev_submited,
        password: new_value,
      };
    });
  };
  //表单提交
  const form_ref = useRef();
  //传递子组件方法给父组件
  useImperativeHandle(ref, () => ({
    dispatch_submit: () => {
      if (username_errors.length > 0 || password_errors.length > 0) {
        return false;
      }
      form_ref.current.dispatchEvent(
        new Event("submit", { cancelable: true, bubbles: true })
      );
      return true;
    },
    dispatch_reset: () => {},
  }));

  //当表单提交时
  const onSubmit = async (e) => {
    e.preventDefault();
    console.log(submited);
    //需要进行错误处理
    try {
      let res = await invoke("login", { user: submited });
      let user_info = res.data;
      console.log(user_info);

      dispatch(save_user_info(user_info));
      addToast({
        title: "登陆成功!将自动跳转",
        timeout: 2000,
        shouldShowTimeoutProgress: true,
        color: "success",
        variant: "bordered",
      });
      setTimeout(() => {
        navigate("/main/home");
      }, 2000);
    } catch (e) {
      //错误处理
      const prefix = "找不到用户,名为: ";
      addToast({
        title: `${prefix}${submited.username}`,
        variant: "bordered",
      });
      dispatch(reset_user_form());
    }
  };
  //表单提交验证规则
  const username_errors = [];
  const password_errors = [];
  //用户名验证规则
  if (submited.username.length > 10 || submited.username.length < 4) {
    username_errors.push("用户名长度必须大于四个字符并且小于十个字符");
  }
  //用户名非法符号校验
  //密码验证规则
  if (submited.password.length < 4) {
    password_errors.push("密码长度必须为大于四个字符");
  }
  // if ((password.match(/[A-Z]/g) || []).length < 1) {
  //   password_errors.push("密码必须包含一个大写字母");
  // }
  if ((submited.password.match(/[^a-z]/gi) || []).length < 1) {
    password_errors.push("密码必须包含一个数字");
  }

  return (
    <Form
      ref={form_ref}
      className="w-[100%] h-[100%] flex-col items-center justify-center"
      onSubmit={onSubmit}
      validationBehavior="native"
    >
      <LoginInput
        inputName={"username"}
        type="text"
        label={"用户名"}
        error_list={username_errors}
        variant={submited.username}
        setVariant={set_submited_username}
      ></LoginInput>
      <LoginInput
        inputName={"password"}
        type="password"
        label={"密码"}
        error_list={password_errors}
        variant={submited.password}
        setVariant={set_submited_password}
      ></LoginInput>
    </Form>
  );
});

export default LoginForm;
